<template>
  <div class="app-container">
    <div class="flex">
      <el-select
        v-model="listQuery.status"
        placeholder="时间"
        style="width: 120px"
        class="filter-item"
      >
        <el-option
          v-for="item in importanceOptions"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
      <el-select
        v-model="listQuery.author"
        placeholder="告警类型"
        clearable
        class="filter-item"
        style="width: 130px"
      >
        <el-option
          v-for="item in calendarTypeOptions"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
      <el-button
        v-waves
        style="margin:0 0 20px 20px;"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        {{ $t('message.layout.search') }}
      </el-button>
       <el-button
      v-waves
			        :loading="downloadLoading"
			        style="margin:0 0 20px 20px;"
			        type="primary"
			        icon="el-icon-document"
			        @click="handleDownload"
			      >
        		  {{ $t('message.layout.excelexport') }}     
      			</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >
      <el-table-column
        label="日期"
        width="150px"
        align="center"
      >
        <template #default="{row}">
          <span
            class="link-type"
          >{{
            row.creationDateTimeStr
          }}</span>
          <!-- <el-tag>{{ row.type }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column
        :label="t('message.layout.title')"
        width="150px"
        align="center"
      >
        <template #default="{row}">
          <span
            class="link-type"
          >{{
            row.sebeiname
          }}</span>
          <!-- <el-tag>{{ row.type }}</el-tag> -->
        </template>
      </el-table-column>
      
      <el-table-column
        label="告警类型"
        width="110px"
        align="center"
      >
        <template #default="{row}">
          <span >{{ row.typeStr }}</span>
        </template>
      </el-table-column>
     
      <el-table-column
        label="告警来源"
        align="center"
        width="150"
      >
        <template #default="{row}">
          <span
            class="link-type"
            @click="handleGetPageviews(row.sourceTarget)"
          >{{ row.sourceTargetStr }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="信息"
        width="150"
        align="center"
      >
        <template #default="{row}">
          <span
            class="link-type"
            @click="handleGetPageviews(row.sourceTarget)"
          >{{ row.errorContentStr }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="内容"
        min-width="150"
        align="center"
      >
        <template #default="{row}">
          <span
            class="link-type"
            @click="handleGetPageviews(row.sourceTarget)"
          >{{ row.content }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('message.layout.actions')"
        align="center"
        width="100"
        class-name="fixed-width"
      >
        <template #default="{row}">
          <el-button  
            type="danger"
            v-if="!row.isverify"          
            size="mini"
            @click="handleVerify(row)"
          >
            未确认
          </el-button>
          <el-button  
            v-if="row.isverify"          
            size="mini"
          >
            已确认
          </el-button>
          
        </template>
      </el-table-column>
     
    </el-table>


    <el-pagination
      :total="total"
      v-show="total > 0"
      v-model:page="listQuery.currentPage"
      v-model:limit="listQuery.pageCount"
      @current-change="handleCurrentChange"
      layout="total,prev, pager, next, jumper"
    />
   <ComplexDialog @updateData="updateData" @createData="createData" ref="dialogPop" v-model="dialogFormVisible" v-model:dialogStatus="dialogStatus"></ComplexDialog>

   
  </div>
</template>

<script lang='ts'>
import {
  defineComponent,
  reactive,
  toRefs,
  ref,
  nextTick,
  onMounted,
  unref,
onUnmounted
} from 'vue'
import { ElForm, ElMessage } from 'element-plus'
import { cloneDeep } from 'lodash'
import {
  getArticles,
  getPageviews,
  createArticle,
  deleteArticle,
  updateArticle,
  defaultArticleModel,
  ArticleType
} from '/@/request/articles'
import { ArticleModel } from '/@/model/articleModel'

import { exportJson2Excel } from '/@/utils/excel';
import { formatJson } from '/@/utils';
import { useI18n } from 'vue-i18n'
//import zhihuiJigouJson from '/@/mock/yujingShezhi.json';
// import Pagination from '@/components/Pagination/index.vue'
import '/@/assets/iconfont/iconfont.css'
import VoiceRecordUnit from '/@/utils/shf/VoiceRecordUnit'
import VoiceUnit from '/@/utils/shf/VoiceUnit'
import Http3DReq from '/@/utils/shf/http/Http3DReq'
import HttpReqApi from '/@/utils/shf/http/HttpReqApi'
import MittUnit, { MittEvent } from '/@/utils/shf/MittUnit'
import Assert from '/@/utils/shf/Assert'
import WarnLogVo from '/@/utils/vo/WarnLogVo'
export default defineComponent({
  components: {
    // Pagination
  },
  setup() {
     
     onMounted(async () => {
    
      console.log(typeof ElForm);
      // dataMap.getList(null, null, 10);
      MittUnit.on(MittEvent.updateEquipSuccess,updateEquipSuccess);
      dataMap.listLoading = false;
      // let res:any = await HttpReqApi.getEquips();
      // console.log("getEquips = ",res);
      // // dataMap.list=res;
      dataMap.getList(1);
    })
    onUnmounted(()=>{
      MittUnit.off(MittEvent.updateEquipSuccess,updateEquipSuccess);
    })
    const updateEquipSuccess = async ()=>{
      ElMessage.success('更新成功');
      dataMap.dialogFormVisible = false;
      let res:any = await HttpReqApi.getEquips();
      console.log("getEquips = ",res);
      dataMap.list=res;
        //  console.log(ArticleModel)
        //     const addData=await HttpReqApi.updateEquip(ArticleModel).then(async() => {
		    //     ElMessage.success('添加成功')
		    //     dataMap.dialogFormVisible = false
		    //     const data = await getArticles(dataMap.listQuery,ArticleType.YJSZ)
		    //     //const data=zhihuiJigouJson        
		    //     dataMap.list = data?.data ?? []
		    //     dataMap.total = data?.total ?? 0
		    //   }).catch(err => {
		    //   ElMessage.warning('添加错误')
		    //  });
    };
    const { t } = useI18n()
    const tagArr = ['温度','湿度','氧气','一氧化碳','二氧化碳','压力','甲烷','渗漏水','入侵','消防烟感','消防温感','消防手报','机电','突发'];
    const calendarTypeOptions = ['一般告警','橙色告警','红色告警'];
    const sourceTypeArr = ["在线检测(ping)","交换机检测(snmp)","ups电源检测(modbus)","监控在线检测(rtsp)"];
	  const calendarTypeKeyValue = calendarTypeOptions.reduce(
      (acc: { [key: string]: string }, cur) => {
        acc[cur.key] = cur.displayName
        return acc
      },
      {}
    ) as { [key: string]: string }
    const dataForm = ref(ElForm)
    const dataMap = reactive({
      tableKey: 0,
      list: Array<ArticleModel>(),
      total: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
        pageCount: 10,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id',
        status:"今日告警"
      },
      listfilter:tagArr.map((item)=>{return {text:item,value:item}}),

	  monObjectOptions:tagArr,
      
      importanceOptions: ['今日告警','历史告警'],
      calendarTypeOptions: calendarTypeOptions,
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],

      statusOptions: ['自动归档', '手动归档'],
      showReviewer: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },

      dialogPageviewsVisible: false,
      pageviewsData: [],
      rules: {
        equipName: [
          { required: true, message: 'name is required', trigger: 'change' }
        ],
        upperLimit: [
          { required: true,pattern: /^[0-9]+.?[0-9]*/,message: 'upper_limit is required', trigger: 'change' }
        ],
        lowerLimit: [
          { required: true,pattern: /^[0-9]+.?[0-9]*/, message: 'lower_limit is required', trigger: 'change' }
        ],
        phoneNum: [
          // { required: true,pattern: /^1\d{10}$/, message: 'phone is required', trigger: 'change' }
          { required: true, message: 'phone is required', trigger: 'change' }
        ],
        warnContent: [
          { required: true, message: 'warnContent is required', trigger: 'change' }
        ],
      },
      downloadLoading: false,
      tempArticleModel: {
        id: 0,
        equipName: '',
        lowerLimit: '',
        upperLimit: '',
        phoneNum: '',
        warnContent: '{}数值，不在安全范围内',
        type: [],
      },
      handleCurrentChange(page?: any) {
        dataMap.getList(page)
      },
      handleSizeChange(val: any) {
        // dataMap.getList(null, null, val)
      },
      async getList(page?: any, total?: any, limit?: any,data?:any) {
        if (page) {
          dataMap.listQuery.currentPage = page;
          let type = "-1";
           if(dataMap.listQuery.author)
          {
            type = calendarTypeOptions.indexOf(dataMap.listQuery.author)+"";
          }
          let res:any;
          if(dataMap.listQuery.status == "今日告警")
          res = await Http3DReq.warnlogListToday({type,currentPage:page-1,pageCount:8});
          else
          res = await Http3DReq.warnlogListHistory({type,currentPage:page-1,pageCount:8});
          if(res)
          {
            let dataArr:any = [];
            for (const datares of res.content) {
              let vo = new WarnLogVo(datares);
              vo.sourceTargetStr = sourceTypeArr[vo.sourceTarget];
              vo.typeStr = calendarTypeOptions[vo.type];
              if(!vo.content)
              {
                vo.content = vo.errorContent
              }
              if(!vo.sourceTargetStr)
              {
                vo.sourceTargetStr = vo.sebeiname+"传感器";
              }
              if(!vo.errorContentStr)
              {
                vo.errorContentStr = "无";
              }
              dataArr.push(vo);
            }
            dataMap.total = res.totalElements;
            dataMap.list = dataArr;
          }
        }
        return;
        
        if (limit) {
          dataMap.listQuery.pageCount = limit
        }
        console.log(total)
        dataMap.listLoading = true

        if (data){
        	dataMap.list = data.data
        	dataMap.total = data.total
        }
        else{
        const data = await getArticles(dataMap.listQuery,ArticleType.YJSZ)
        //const data=zhihuiJigouJson        
        dataMap.list = data?.data ?? []
        dataMap.total = data?.total ?? 0
        }

        // Just to simulate the time of the request
        setTimeout(() => {
          dataMap.listLoading = false
        }, 0.5 * 1000)
      },
      async handleFilter() {
         dataMap.getList(1);
      },
      listfilterFun(
        value: string,
        row: any
      ) {
        return row.equipName === value
      },
      handleModifyStatus(row: any, status: string) {
      /*
        ElMessage.success({
          message: '操作成功',
          type: 'success'
        })
        row.status = status*/
      },
      sortChange(data: any) {
        const { prop, order } = data
        if (prop === 'id') {
          dataMap.sortByID(order)
        }
      },
      sortByID(order: string) {
        if (order === 'ascending') {
          dataMap.listQuery.sort = '+id'
        } else {
          dataMap.listQuery.sort = '-id'
        }
        dataMap.handleFilter()
      },
      getSortClass(key: string) {
        const sort = dataMap.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      },
      resetTempArticleModel() {
        dataMap.tempArticleModel = {
        id: 0,
        equipName: '',
        lowerLimit: '',
        upperLimit: '',
        phoneNum: '',
        warnContent: '{}数值，不在安全范围内',
        type: [],
      };
      },
      handleCreate() {
        console.log('添加了')
        dataMap.resetTempArticleModel()
        dataMap.dialogStatus = 'create'
        dataMap.dialogFormVisible = true
        nextTick(() => {
          (dataForm.value as typeof ElForm).clearValidate()
        })
      },
      createData() {
        const form = unref(dataForm)
        form.validate(async(valid: any) => {
          if (valid) {
            const ArticleModel = dataMap.tempArticleModel;
            if(ArticleModel.warnContent.indexOf("{}") == -1)
            Assert.isFalse(true,"告警内容缺少{}");
            if((ArticleModel.type as any).indexOf("电话通知") != -1)
            {
              VoiceUnit.start(ArticleModel,ArticleModel.warnContent);
              return;
            }
            VoiceUnit.updateEquip(ArticleModel);
            return;
            
            //ArticleModel.id = Math.round(Math.random() * 100) + 1024 // mock a id
            //ArticleModel.author = 'RCYJ_Scy'
           
		     
			/*
            if (addData?data.id) {
              alert(addData.data.id)
              console.log(addData)
              dataMap.list.unshift(addData.data)
            }
			
            dataMap.dialogFormVisible = false
            ElMessage.success({
              message: '创建成功',
              type: 'success',
              duration: 2000
            })*/
            
          }
        })
      },

      handleUpdate(row: any) {

        console.log('添加了');
        dataMap.resetTempArticleModel();
        dataMap.tempArticleModel.id = row.id;
        dataMap.tempArticleModel.equipName = row.equipName;
        dataMap.tempArticleModel.lowerLimit = row.lowerLimit;
        dataMap.tempArticleModel.upperLimit = row.upperLimit;
        dataMap.tempArticleModel.warnContent = row.warnContent;
        dataMap.tempArticleModel.phoneNum = row.phoneNum;
        if(row.smsNotify)
         (dataMap.tempArticleModel.type as any).push("短信通知");
          if(row.phoneNotify)
         (dataMap.tempArticleModel.type as any).push("电话通知");
        dataMap.dialogStatus = 'update';
        dataMap.dialogFormVisible = true;
        nextTick(() => {
          (dataForm.value as typeof ElForm).clearValidate()
        })
      },
      updateData() {
        const form = unref(dataForm)
        form.validate(async(valid: any) => {
          if (valid) {
            const tempData = Object.assign({}, dataMap.tempArticleModel)
            //tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            console.log(tempData)
            const data = await updateArticle(tempData,ArticleType.YJSZ).then(async()=>{
	        	ElMessage.success('更新成功')
		        dataMap.dialogFormVisible = false
		        const data = await getArticles(dataMap.listQuery,ArticleType.YJSZ)		                
		        dataMap.list = data?.data ?? []
		        dataMap.total = data?.total ?? 0	
            }).catch(err => {
		      ElMessage.warning('更新失败')
		    });
			/*
            console.log(data, '-----------------')
            if (data) {
              const index = dataMap.list.findIndex(
                (v) => v.id === data.data.id
              )
              dataMap.list.splice(index, 1, data.data)
            }

            dataMap.dialogFormVisible = false
            ElMessage.success({
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            */
          }
        })
      },
      async handleDelete(row: any, index: number) {
      	await deleteArticle(row.id,ArticleType.YJSZ).then(()=>{
        ElMessage.success({
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        dataMap.list.splice(index, 1)
        }).catch(err => {
	      ElMessage.warning('删除失败')
	     });
      },
      async handleVerify(row:any){
        let res = await Http3DReq.warnLogVerify({id:row.id});
        if(res)
        {
          row.isverify = true;
        }
      },
      async handleGetPageviews(pageviews: string) {
        const data = await getPageviews({ pageviews })
        //const data = zhihuiJigouJson.data;
        dataMap.pageviewsData = data?.data.pageviews
        console.log(dataMap.pageviewsData)
        dataMap.dialogPageviewsVisible = true
      },
      async handleDownload() {
        dataMap.downloadLoading = true;
          let res:any;
          if(dataMap.listQuery.status == "今日告警")
          res = await Http3DReq.warnlogListToday({type:"-1",currentPage:0,pageCount:900});
          else
          res = await Http3DReq.warnlogListHistory({type:"-1",currentPage:0,pageCount:900});
          if(res)
          {
            let dataArr:any = [];
            for (const datares of res.content) {
              let vo = new WarnLogVo(datares);
              vo.sourceTargetStr = sourceTypeArr[vo.sourceTarget];
              vo.typeStr = calendarTypeOptions[vo.type];
              dataArr.push(vo);
            }
            const tHeader = ['日期','名称', '告警类型', '告警来源',"信息", '内容'];
            const filterVal = ['creationDateTimeStr','sebeiname', 'typeStr', 'sourceTargetStr','errorContentStr', 'content'];

            let data = formatJson(filterVal, dataArr, true);
            exportJson2Excel(tHeader, data, '预警日志', undefined, undefined, true, 'xlsx');

          }
          dataMap.downloadLoading = false;

      },
      typeFilter: (type: string) => {
        return calendarTypeKeyValue[type]
      },
     
   
      
    })
    
    return { t,...toRefs(dataMap), dataForm }
  }
})
</script>
